import * as storage from '@/assets/js/storage'
import * as pearuserAPI from "@/pearapi/user";

export default {
    pageLoading: ({ commit }, status) => commit('PAGE_LOADING', status),
    windowLoading: ({ commit }, status) => commit('WINDOW_LOADING', status),
    setBoundClient: ({ commit }, data) => commit('SET_BOUND_CLIENT', data),
    initData: ({ dispatch }) => dispatch('INIT_DATA'),
    sendMessage: ({ dispatch }, content) => dispatch('SEND_MESSAGE', content),
    selectSession: ({ dispatch }, id) => dispatch('SELECT_SESSION', id),
    search: ({ dispatch }, value) => dispatch('SET_FILTER_KEY', value),
    refreshName: ({ dispatch }, username) => dispatch('REFRESH_NAME', username),
    setCurUser: ({ dispatch }, userinfo) => dispatch('SET_CUR_USER', userinfo),
    setUserInfo: ({ dispatch }, userinfo) => dispatch('SET_USER_INFO', userinfo),
    setLogged: ({ commit }, data) => {
        storage.setStore('tokenList', data.tokenList);
        storage.setStore('userInfo', data.userInfo);
        commit('SET_LOGGED', data);
    },
    setUser: ({ commit }, data) => {
        storage.setStore('userInfo', data);
        commit('SET_USER', data);
    },
    setLogout: ({ commit }) => {
        storage.removeStore('tokenList');
        storage.removeStore('userInfo');
        commit('SET_LOGOUT');
    },
    setTheme: ({ commit }, theme) => {
        storage.setStore('theme', theme);
        commit('SET_THEME', theme);
    },
    setOrganizationList: ({ commit }, data) => {
        storage.setStore('organizationList', data);
        commit('SET_ORGANIZATION_LIST', data);
    },
    setCurrentOrganization: ({ commit }, data) => {
        storage.setStore('currentOrganization', data);
        commit('SET_CURRENT_ORGANIZATION', data);
    },
    setSystem: ({ commit }, data) => {
        storage.setStore('system', data);
        commit('SET_SYSTEM', data);
    },
    getUser: ({ commit }) => {
        pearuserAPI._currentMember().then(res => {
            if (!res.data) {
                storage.removeStore('tokenList');
                storage.removeStore('userInfo');
                commit('SET_LOGOUT');
            } else {
                storage.setStore('userInfo', res.data);
                commit('SET_USER', res.data);
            }
        });
    },
    checkLogin: ({ commit }) => {
        pearuserAPI._checkLogin().then(res => {
            if (res.data) {
                const obj = {
                    userInfo: res.data.member,
                    tokenList: res.data.tokenList
                };
                storage.setStore('tokenList', obj.tokenList);
                storage.setStore('userInfo', obj.userInfo);
                commit('SET_LOGGED', obj);
            } else {
                storage.removeStore('tokenList');
                storage.removeStore('userInfo');
                commit('SET_LOGOUT');
            }
        });
    },
}